package com.ice.app.project.scheduleJob.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.util.StringUtil;
import com.ice.app.project.entity.ScheduleJob;
import com.ice.app.project.mapper.ScheduleJobMapper;
import com.iceframework.core.quartz.utils.ScheduleJobUtils;
import com.iceframework.core.utils.KeyUtils;
import com.iceframework.core.utils.WebUtils;

/**
 * 
 * 业务逻辑层： 定时任务表
 * 
 * @author Mr.Palo
 * @email 442803840@qq.com
 * @date 2019-07-20 05:55:35
 */
@Service
public class ScheduleJobService {

	@Autowired
	private ScheduleJobMapper scheduleJobMapper;

	private static final String JOB_TYPE_CLASS = "Class";
	private static final String JOB_TYPE_URL = "Url";
	private static final String JOB_STATE_ACTIVE = "Active";
	private static final String JOB_STATE_STOP = "Stop";

	// ----------------------------------------自动生成--------------------------------------------

	/**
	 * 菜单保存
	 * 
	 * @param scheduleJob
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public boolean saveScheduleJob(ScheduleJob scheduleJob) throws Exception {
		if (StringUtil.isNotEmpty(scheduleJob.getId())) {
			// 修改操作
			ScheduleJob old = this.getScheduleJob(scheduleJob.getId());
			scheduleJob.setUpdateBy(WebUtils.getUserId());
			scheduleJob.setUpdateDate(new Date());
			scheduleJob.setJobStatus(old.getJobStatus());
			if (old != null) {
				if (scheduleJobMapper.updateByPrimaryKeySelective(scheduleJob) > 0) {
					// 移除任务
					ScheduleJobUtils.removeJob(old.getJobName(), old.getJobGroup());
					// 添加任务
					addJob(scheduleJob);
					return true;
				}
			}
			return false;
		} else {
			// 保存操作
			String key = KeyUtils.genKey("ScheduleJob");
			scheduleJob.setId(key);
			scheduleJob.setJobStatus(JOB_STATE_ACTIVE);
			scheduleJob.setCreateBy(WebUtils.getUserName());
			scheduleJob.setCreateDate(new Date());
			scheduleJob.setUpdateBy(WebUtils.getUserName());
			scheduleJob.setUpdateDate(new Date());
			if (scheduleJobMapper.insertSelective(scheduleJob) > 0) {
				addJob(scheduleJob);
				return true;
			}
		}
		return false;
	}

	/**
	 * 添加任务
	 * 
	 * @param scheduleJob
	 * @throws Exception
	 */
	private void addJob(ScheduleJob scheduleJob) throws Exception {
		if (!JOB_STATE_ACTIVE.equals(scheduleJob.getJobStatus())) {
			return;
		}
		if (JOB_TYPE_CLASS.equals(scheduleJob.getJobType())) {
			ScheduleJobUtils.addJob(scheduleJob.getJobName(), scheduleJob.getJobGroup(), scheduleJob.getJobExec(), scheduleJob.getCronExpression());
		} else if (JOB_TYPE_URL.equals(scheduleJob.getJobType())) {
			ScheduleJobUtils.addHttpClientJob(scheduleJob.getJobName(), scheduleJob.getJobGroup(), scheduleJob.getJobExec(), scheduleJob.getCronExpression());
		}
	}

	/**
	 * 根据主键删除菜单
	 * 
	 * @param key
	 * @return
	 */
	@Transactional
	public boolean deleteScheduleJob(String key) {
		return scheduleJobMapper.deleteByPrimaryKey(key) > 0;
	}

	/**
	 * 根据多个主键删除菜单
	 * 
	 * @param keys
	 * @return
	 */
	@Transactional
	public boolean deleteScheduleJobs(String keys) {
		if (!StringUtils.isEmpty(keys)) {
			String[] strs = keys.split(",");
			for (String key : strs) {
				try {
					stopJob(key);
					this.deleteScheduleJob(key);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return true;
		}
		return false;
	}

	/**
	 * 根据主键获取菜单实体
	 * 
	 * @param key
	 * @return
	 */
	public ScheduleJob getScheduleJob(String key) {
		return scheduleJobMapper.selectByPrimaryKey(key);
	}

	/**
	 * 根据给定条件获取菜单实体集合
	 * 
	 * @param key
	 * @return
	 */
	public List<ScheduleJob> getScheduleJobs(ScheduleJob scheduleJob) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("scheduleJob", scheduleJob);
		return scheduleJobMapper.selectByFilter(map);
	}

	// ----------------------------------------自定义（Public）---------------------------------------------

	/**
	 * 初始化所有任务
	 * 
	 * @throws Exception
	 */
	public void initJobs() {
		ScheduleJob job = new ScheduleJob();
		job.setJobStatus(JOB_STATE_ACTIVE);
		// 获取所有任务
		List<ScheduleJob> scheduleJobs = getScheduleJobs(job);
		// 将任务激活
		for (ScheduleJob scheduleJob : scheduleJobs) {
			try {
				addJob(scheduleJob);
			} catch (Exception e) {

			}
		}
	}

	/**
	 * 激活任务
	 * 
	 * @param key
	 * @throws Exception
	 */
	@Transactional
	public void activeJob(String key) throws Exception {
		ScheduleJob scheduleJob = getScheduleJob(key);
		scheduleJob.setJobStatus(JOB_STATE_ACTIVE);
		scheduleJobMapper.updateByPrimaryKeySelective(scheduleJob);
		if (ScheduleJobUtils.existJob(scheduleJob.getJobName(), scheduleJob.getJobGroup())) {
			ScheduleJobUtils.removeJob(scheduleJob.getJobName(), scheduleJob.getJobGroup());
		}
		if (JOB_TYPE_CLASS.equals(scheduleJob.getJobType())) {
			ScheduleJobUtils.addJob(scheduleJob.getJobName(), scheduleJob.getJobGroup(), scheduleJob.getJobExec(), scheduleJob.getCronExpression());
		} else if (JOB_TYPE_URL.equals(scheduleJob.getJobType())) {
			ScheduleJobUtils.addHttpClientJob(scheduleJob.getJobName(), scheduleJob.getJobGroup(), scheduleJob.getJobExec(), scheduleJob.getCronExpression());
		}
	}

	/**
	 * 停止任务
	 * 
	 * @param key
	 * @throws Exception
	 */
	@Transactional
	public void stopJob(String key) throws Exception {
		ScheduleJob scheduleJob = getScheduleJob(key);
		scheduleJob.setJobStatus(JOB_STATE_STOP);
		scheduleJobMapper.updateByPrimaryKeySelective(scheduleJob);
		if (ScheduleJobUtils.existJob(scheduleJob.getJobName(), scheduleJob.getJobGroup())) {
			ScheduleJobUtils.removeJob(scheduleJob.getJobName(), scheduleJob.getJobGroup());
		}
	}

	/**
	 * 启动定时器
	 * 
	 * @param key
	 * @throws Exception
	 */
	@Transactional
	public void startJobs() throws Exception {
		ScheduleJobUtils.startJobs();
	}

	/**
	 * 停止定时器
	 * 
	 * @param key
	 * @throws Exception
	 */
	@Transactional
	public void shutdownJobs() throws Exception {
		ScheduleJobUtils.shutdownJobs();
	}

}